<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF 预览 - PDF.js</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
    <style>
        #pdfCanvas {
            border: 1px solid #ccc;
            width: 100%;
            max-width: 800px;
            margin: 20px 0;
        }
        #pdfViewer {
            width: 100%;
            text-align: center;
        }
    </style>
</head>
<body>
<h2>PDF 预览</h2>

<!-- 输入框用于输入 PDF 链接 -->
<input type="text" id="pdfUrl" placeholder="请输入 PDF 链接" style="width: 80%;">
<button onclick="loadPdf()">加载 PDF</button>

<!-- PDF 预览区域 -->
<div id="pdfViewer">
    <canvas id="pdfCanvas"></canvas>
</div>

<script>
        const pdfjsLib = window['pdfjs-dist/build/pdf'];
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';

        function loadPdf() {
            const url = document.getElementById('pdfUrl').value;
            if (url) {
                // 获取 PDF 文件
                const loadingTask = pdfjsLib.getDocument(url);
                loadingTask.promise.then(function(pdf) {
                    // 获取第一页
                    pdf.getPage(1).then(function(page) {
                        const scale = 1.5;
                        const viewport = page.getViewport({ scale: scale });

                        // 获取 canvas 并设置其尺寸
                        const canvas = document.getElementById('pdfCanvas');
                        const context = canvas.getContext('2d');
                        canvas.height = viewport.height;
                        canvas.width = viewport.width;

                        // 渲染页面
                        const renderContext = {
                            canvasContext: context,
                            viewport: viewport
                        };
                        page.render(renderContext);
                    });
                }).catch(function(error) {
                    console.error('加载 PDF 时出错: ' + error.message);
                });
            } else {
                alert('请输入有效的 PDF 链接！');
            }
        }
    </script>
</body>
</html>
